﻿using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;

namespace template_dll.Dialogs
{
	/// <summary>
	/// Wrapper over MSDASC "Data Link Property" dialog.
	/// </summary>
	internal class DataLinkDialog
	{
		private readonly object _dialog;

		/// <summary>
		/// Creates new dialog.
		/// </summary>
		/// <param name="parent"></param>
		public DataLinkDialog(Control parent)
		{
			try
			{
				_dialog = RuntimeHelpers.GetObjectValue(Interaction.CreateObject("DataLinks", ""));
				NewLateBinding.LateSet(_dialog, null, "hWnd", new object[] { parent.Handle.ToInt32() }, null, null);
			}
			catch (Exception ex)
			{
				Debug.WriteLine(ex);
			}
		}

		/// <summary>
		/// Checks if dialog is available.
		/// </summary>
		/// <returns></returns>
		public bool IsDialogAvailable()
		{
			return _dialog != null;
		}

		/// <summary>
		/// Shows new dialog.
		/// </summary>
		/// <returns>Connection string.</returns>
		public string ShowDialog()
		{
			if (! IsDialogAvailable())
				throw new InvalidOperationException("Data Link Property dialog is not available.");

			string connectionString = string.Empty;
			try
			{
				object o = RuntimeHelpers.GetObjectValue(NewLateBinding.LateGet(_dialog, null, "PromptNew", new object[0], null, null, null));
				if (o == null)
					return connectionString;
				connectionString = NewLateBinding.LateGet(o, null, "ConnectionString", new object[0], null, null, null).ToString();
			}
			catch (Exception ex)
			{
				Debug.WriteLine(ex);
			}
			return connectionString;
		}
	}
}
